/*
 * @Author: tcosfish
 * @Date: 2022-07-26 10:17:08
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-18 16:37:21
 * @FilePath: \loadFile\src\excel\feat\read_month_repo.ts
 */

import xlsx from "xlsx"

import { existsSync } from "fs"

const header: string[] = [
  "code",
  "name",
  "",
  "",
  "",
  "debit_amount",
  "credit_amount",
  "",
  "",
  "debit_closing_balance",
  "credit_closing_balance",
  "id",
]

export function read_month_repo(filepath: string, initHeader: any = header) {
  // 0. 判断xlsx中的路径是否存在
  if (existsSync(filepath.replace("xlsx", "xls"))) {
    console.log("文件已存在")
    console.log("正在查找文件对应缓存...")
    console.log("已返回文件缓存")
  } else {
    console.log("文件不存在, 正在执行运行逻辑")
  }

  // 1. 从上传的文件中获取数据
  const wb = xlsx.readFile(filepath)
  const wb_data: any[] = []

  for (const sheet_name of wb.SheetNames) {
    // 1.转化为 JSON 数据
    const sheet = wb.Sheets[sheet_name]
    const sht = xlsx.utils.sheet_to_json(sheet, {
      header: initHeader,
      skipHidden: true,
    })

    // 2. 对key为空字符的数据进行处理
    let new_sht_data: any[] = []
    sht.forEach((row: any) => {
      if (row.id !== "ID") {
        let row_data: any = {}
        for (const key in row) {
          if (key !== "") {
            row_data[key] = row[key]
          }
        }
        new_sht_data.push(row_data)
      }
    })
    wb_data.push(new_sht_data)
  }

  return wb_data
}
